#!/usr/bin/env python
import os
import json
import sys
import subprocess
import mysql.connector
from urlparse import parse_qs
from mysql.connector import Error
import cgi
import logging  
import logging.handlers  
import requests
import json
import ConfigParser

config = ConfigParser.ConfigParser()
config.read('/etc/fileserver/config.ini')

class FileStatus:
    NOT_SCANNED = 0 
    SCANNING = 1 
    NORMAL = 2 
    EXCEPTION = 3

MYSQL_CONFIG = { 
    'host': config.get("mysql","host"),
    'user': config.get("mysql","user"),
    'password': config.get("mysql","password"),
    'database': config.get("mysql","database"),
    'charset': config.get("mysql","charset"),
    'port'   : config.get("mysql","port")
}


logging.basicConfig(level=logging.DEBUG,
                                format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                                datefmt='%Y-%m-%d %H:%M:%S',
                                stream=sys.stderr) 
logger = logging.getLogger(__name__)

def connect_to_database():
    try:
        cnx = mysql.connector.connect(**MYSQL_CONFIG)
        return cnx 
    except Error as err:
        logger.info("Error connecting to MySQL: %s" % err)
        return None

def close_database_connection(cnx):
    if cnx is not None:
        cnx.close()


def check_security_status_in_db(file_name):
    cnx = connect_to_database()
    if cnx is None:
        return FileStatus.NOT_SCANNED, None
    status = FileStatus.NOT_SCANNED
    virus_details = None
    cursor = None
    try:
        cursor = cnx.cursor()
        query = "SELECT status, virus_details FROM filesecurity WHERE file_name = %s"
        cursor.execute(query, (file_name,))
        results = cursor.fetchall()
        for result in results:
           if result:
               status, virus_details = result
           else:
              status=FileStatus.NOT_SCANNED
              virus_details = None 
        
        #result = cursor.fetchone()
        #if result:
        #    status, virus_details = result
        #    return status, virus_details
        #else:
        #    return FileStatus.NOT_SCANNED, None
        return status, virus_details
    finally:
        if cursor is not None:
            cursor.close()
        close_database_connection(cnx)


#def check_security_status(file_name):
#    elif os.path.isfile('/var/www/cgi-bin/inject.txt') and file_name in open('/var/www/cgi-bin/inject.txt').read():
#        return 3
#    else:
#        return 1
#

#def get_file_list(directory):
#    file_info_list = []
#    if not os.path.exists(directory):
#        return file_info_list
#    for file_name in os.listdir(directory):
#        file_path = os.path.join(directory, file_name)
#        file_check_name=file_path.replace('/var/www/html/', "")
#        #security_status = check_security_status(file_name)
#        #logger.error(file_check_name) 
#        security_status, virus_details = check_security_status_in_db(file_check_name)
#        file_info = {
#            'name': file_name,
#            'download_path': file_path.replace('/var/www/html/', "/fileserver/delayed_download.php?file="),
#            'view_path': file_path.replace('/var/www/html/', "/fileserver/"),
#            'deletefile_path': file_path.replace('/var/www/html/', ''),
#            'type': 'directory' if os.path.isdir(file_path) else 'file',
#            #'security': security_status
#            'security': security_status,
#            'virus_details': virus_details,
#        }
#        if os.path.isdir(file_path):
#            file_info['children'] = get_file_list(file_path)
#        file_info_list.append(file_info)
#    return file_info_list

def get_file_list(directory, base_path=""):
    file_info_list = []
    if not os.path.exists(directory):
        return file_info_list
    try:
        for file_name in os.listdir(directory):
            file_path = os.path.join(directory, file_name)
            relative_path = os.path.join(base_path, file_name)
            file_check_name = file_path.replace('/var/www/html/', "")
            security_status, virus_details = check_security_status_in_db(file_check_name)
            if os.path.isdir(file_path):
                subdirectory_info_list = get_file_list(file_path, relative_path)
                if subdirectory_info_list:
                    file_info_list.extend(subdirectory_info_list)
            else:
                if security_status == FileStatus.NOT_SCANNED:
                    file_info_list.append({'name': relative_path})
    except OSError as e:
        print("Error accessing directory: {}".format(e))
    return file_info_list



query_string = os.environ.get('QUERY_STRING', '')

logger.info("Query string: {}\n".format(query_string))

params = parse_qs(query_string)

#get cookie
cookie_header = os.environ.get('HTTP_COOKIE', '') 
logger.error(cookie_header)
cookie=""
if cookie_header:
    cookies = cgi.parse_qs(cookie_header)
    for cookie_name, cookie_value in cookies.items():  
        if cookie_name == "RBIID":
            logger.error(cookie_name)  
            cookie = {
               'RBIID':cookie_value[0]
              }
            break
if cookie: 
    #url = "http://browser.rbi.afafa.club/manager/server/v1.0/loginInfo"    
    url = config.get("sys","cookies_url")    
    logger.error(cookie)

    response = requests.get(url, cookies=cookie) 
    info = response.json()
    logger.error(info["login_info"]["user_name"])
    user_name = ""
    if response.status_code == 200:  
        user_name = info["login_info"]["user_name"]
        logger.info("get user_name:%s",user_name)
    else:
        logger.error("get userinfo failed")
        response = {
            "get user failed"
        }
        print(json.dumps(reponse))
    directory = "/var/www/html/"+user_name
else:
    directory = params.get('directory', ['/var/www/html'])[0]
    if "/var/www/html" not in directory:
        directory="/var/www/html/" + directory

logger.info("Directory: {}\n".format(directory))

file_list = get_file_list(directory)

response = {
    'file_list': file_list
}

print("Content-Type: application/json\n\n")

print(json.dumps(response))
